<template>
  <div class="course-list-page">
    <!-- 搜索栏 -->
    <div class="search-section">
      <div class="search-bar">
        <input
          v-model="searchParams.title"
          type="text"
          placeholder="请搜索课程名称..."
          class="search-input"
        />
        <n-button type="primary" @click="handleSearch" class="search-btn"> 搜索 </n-button>
      </div>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <div class="filter-header" @click="toggleFilters">
        <h3>筛选条件</h3>
        <span class="toggle-icon" :class="{ expanded: filtersExpanded }">▼</span>
      </div>

      <div class="filter-content" :class="{ expanded: filtersExpanded }">
        <!-- 难度等级 -->
        <div class="filter-group">
          <label class="filter-label">难度等级</label>
          <div class="filter-options">
            <button
              v-for="item in difficultyLevelOptions"
              :key="item.dictValue"
              @click="selectFilter('difficultyLevel', item.dictValue)"
              :class="[
                'filter-option',
                { active: searchParams.difficultyLevel === item.dictValue },
              ]"
            >
              {{ item.dictLabel }}
            </button>
          </div>
        </div>

        <!-- 专业分类 -->
        <div class="filter-group">
          <label class="filter-label">专业分类</label>
          <div class="filter-options">
            <button
              v-for="item in courseTypeOptions"
              :key="item.dictValue"
              @click="selectFilter('courseType', item.dictValue)"
              :class="['filter-option', { active: searchParams.courseType === item.dictValue }]"
            >
              {{ item.dictLabel }}
            </button>
          </div>
        </div>

        <!-- 价格范围 -->
        <div class="filter-group">
          <label class="filter-label">价格范围</label>
          <div class="filter-options">
            <button
              v-for="price in priceRanges"
              :key="price"
              @click="selectFilter('price', price)"
              :class="['filter-option', { active: searchParams.price === price }]"
            >
              {{ price }}
            </button>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="filter-actions">
          <button @click="clearFilters" class="clear-btn">清除筛选</button>
          <!--          <button @click="applyFilters" class="apply-btn">应用筛选</button>-->
        </div>
      </div>
    </div>

    <!-- 排序和结果统计 -->
    <div class="results-header">
      <div class="results-info">
        <span>共找到 {{ pages }} 门课程</span>
      </div>
    </div>

    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>正在加载课程数据...</p>
    </div>
    <div v-else-if="dataList.length === 0" class="empty-state">
      <div class="empty-icon">
        <i class="fas fa-book-open"></i>
      </div>
      <h2 class="empty-title">暂无课程</h2>
      <p class="empty-desc">该分类无任何课程</p>
    </div>
    <!-- 课程网格 -->
    <n-grid x-gap="30" :cols="5">
      <n-gi
        v-for="course in dataList"
        :key="course.id"
        class="course-card"
        @click="viewCourse(course.courseId)"
      >
        <div class="course-image-container">
          <n-image
            v-if="course.coverUrl"
            :src="course.coverUrl"
            class="course-image"
            :img-props="{ style: { width: '100%' } }"
          />
          <div v-else class="no-image">
            {{ course.title }}
          </div>
          <div class="course-badge" v-if="course.isHot">🔥 热门</div>
          <div class="course-level">{{ course.classifyName }}</div>
        </div>
        <div class="course-content">
          <h3 class="course-title">{{ course.title }}</h3>
          <p class="course-description">{{ course.description || '无描述' }}</p>
          <div class="course-meta">
            <!--            <div class="instructor">-->
            <!--              <img-->
            <!--                :src="course.instructor.avatar"-->
            <!--                :alt="course.instructor.name"-->
            <!--                class="instructor-avatar"-->
            <!--              />-->
            <!--              <span>{{ course.instructor.name }}</span>-->
            <!--            </div>-->
            <div class="course-stats">
              <!--              <span class="rating">⭐ {{ course.rating || 0 }}</span>-->
              <span class="students">{{ course.viewCount || 0 }}人学习</span>
            </div>
          </div>
          <div class="course-footer">
            <div class="course-price">
              <span class="current-price">¥{{ course.price || '00.00' }}</span>
              <!--              <span v-if="course.originalPrice" class="original-price"-->
              <!--                >¥{{ course.originalPrice || '00.00' }}</span-->
              <!--              >-->
            </div>
            <div class="course-type">{{ course.difficultyLevelName || '适合所有人' }}</div>
          </div>
        </div>
      </n-gi>
    </n-grid>
    <div class="flex justify-center margin-top-20">
      <n-pagination
        v-model:page="pageNum"
        :page-count="pages"
        size="large"
        :on-update:page="pageUpdate"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, onMounted } from 'vue';
  import { getAllCourseList } from '@/api/course/index';
  import { useRoute, useRouter } from 'vue-router';
  import { getDictApi } from '@/api/common';

  const route = useRoute();
  const router = useRouter();

  const filtersExpanded = ref(false);
  const searchParams = ref({
    title: '',
    difficultyLevel: '',
    classify: '',
    courseType: '',
    type: '',
    price: '',
  });

  // 筛选选项
  const dictMapping = {
    0: 'major_type',
    1: 'skill_type',
    2: 'empowerment_type',
    3: 'guide_type',
    4: 'case_type',
    5: 'tool_type',
  };
  const difficultyLevelOptions = ref<any[]>([]);
  const courseTypeOptions = ref<any[]>([]);

  async function getDifficultyLevelDict() {
    const data: any = await getDictApi('difficulty_level');
    difficultyLevelOptions.value = data || [];
  }

  getDifficultyLevelDict();

  async function getCourseTypeDict(classifyType: any) {
    let courseType = dictMapping[classifyType];
    const data: any = await getDictApi(courseType);
    courseTypeOptions.value = data || [];
  }

  const priceRanges = ref(['免费', '0-100元', '100-500元', '500-1000元', '1000元以上']);

  // const allCourses = ref([
  //   {
  //     id: 1,
  //     title: 'Python机器学习实战',
  //     description: '从零开始学习机器学习，掌握核心算法和实际应用',
  //     image: 'https://images.unsplash.com/photo-1555949963-aa79dcee981c?w=400&h=250&fit=crop',
  //     instructor: {
  //       name: '张教授',
  //       avatar:
  //         'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=40&h=40&fit=crop&crop=face',
  //     },
  //     rating: 4.8,
  //     students: 1234,
  //     price: 299,
  //     originalPrice: 399,
  //     level: '中级',
  //     type: '录播课程',
  //     major: '机器学习',
  //     isHot: true,
  //   },
  // ]);

  function toggleFilters() {
    filtersExpanded.value = !filtersExpanded.value;
  }

  function selectFilter(type: any, value: any) {
    if (searchParams.value[type] === value) {
      searchParams.value[type] = '';
    } else {
      searchParams.value[type] = value;
    }

    handleSearch();
  }

  function clearFilters() {
    searchParams.value = {
      title: '',
      difficultyLevel: '',
      classify: '',
      courseType: '',
      type: '',
      price: '',
    };
  }

  function viewCourse(courseId: any) {
    // 跳转到课程详情页
    router.push({
      name: 'Video', // 使用路由名称
      query: {
        courseId: courseId,
      },
    });
  }

  // 分页参数
  const pageNum = ref(1);
  const pageSize = 10;
  const loading = ref(false);
  const isLastPage = ref(false);
  const pages = ref(0);
  const dataList = ref<any[]>([]);

  function handleSearch() {
    resetPage();
    loadData();
  }

  async function loadData() {
    if (loading.value || isLastPage.value) return;

    loading.value = true;
    try {
      const params = {
        pageNum: pageNum.value,
        pageSize: pageSize,
        ...searchParams.value,
      };

      const data: any = await getAllCourseList(params);
      dataList.value = data.records || [];
      pages.value = data.pages;
      if (dataList.value.length < 10) {
        isLastPage.value = true;
      }
    } catch (error) {
      console.error('error:', error);
    } finally {
      loading.value = false;
    }
  }

  function resetPage() {
    pageNum.value = 1;
    isLastPage.value = false;
    dataList.value = [];
  }

  function pageUpdate(num: any) {
    pageNum.value = num;
    loadData();
  }

  onMounted(() => {
    loadData();
  });

  // 监听路由变化
  watch(
    () => route.name,
    (newParams: any) => {
      console.log('路由参数变化:', newParams);
      if (newParams) {
        const parts = newParams.split('_');
        searchParams.value.classify = parts[parts.length - 1];
        getCourseTypeDict(searchParams.value.classify);
      }
    },
    { immediate: true }
  );
</script>

<style scoped>
  .course-list-page {
    max-width: 1500px;
    margin: 0 auto;
    padding: 20px;
  }

  /* 搜索栏 */
  .search-section {
    margin-bottom: 30px;
  }

  .search-bar {
    display: flex;
    align-items: center;
    gap: 10px;
    max-width: 600px;
    margin: 0 auto;
  }

  .search-input {
    flex: 1;
    height: 45px;
    padding: 0 10px;
    border: 2px solid #e2e8f0;
    border-radius: 8px;
    font-size: 16px;
    transition: border-color 0.3s;
  }

  .search-input:focus {
    outline: none;
    border-color: #d174df;
    box-shadow: 0 0 0 4px rgba(209, 116, 223, 0.1);
    background: white;
  }

  .search-input:placeholder {
    color: #9ca3af;
  }

  .search-btn {
    height: 40px;
  }

  /* 筛选区域 */
  .filter-section {
    background: white;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    margin-bottom: 30px;
    overflow: hidden;
  }

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 20px;
    background: #f7fafc;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .filter-header:hover {
    background: #edf2f7;
  }

  .filter-header h3 {
    margin: 0;
    font-size: 1rem;
    color: #2d3748;
  }

  .toggle-icon {
    font-size: 12px;
    color: #718096;
    transition: transform 0.3s;
  }

  .toggle-icon.expanded {
    transform: rotate(180deg);
  }

  .filter-content {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s ease-out;
    display: none;
  }

  .filter-content.expanded {
    max-height: 1000px;
    display: block;
    padding: 20px;
  }

  .filter-group {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20px;
    gap: 20px;
  }

  .filter-label {
    min-width: 100px;
    font-weight: 600;
    color: #2d3748;
    padding-top: 8px;
  }

  .filter-options {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    flex: 1;
  }

  .filter-option {
    padding: 8px 16px;
    border: 1px solid #e2e8f0;
    border-radius: 20px;
    background: white;
    color: #4a5568;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
  }

  .filter-option:hover {
    border-color: #3182ce;
    color: #3182ce;
  }

  .filter-option.active {
    background: #3182ce;
    color: white;
    border-color: #3182ce;
  }

  .filter-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #e2e8f0;
  }

  .clear-btn,
  .apply-btn {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    transition: background-color 0.3s;
  }

  .clear-btn {
    background: #f7fafc;
    color: #4a5568;
    border: 1px solid #e2e8f0;
  }

  .clear-btn:hover {
    background: #edf2f7;
  }

  .apply-btn {
    background: #3182ce;
    color: white;
  }

  .apply-btn:hover {
    background: #2c5aa0;
  }

  /* 结果统计和排序 */
  .results-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 15px 0;
    border-bottom: 1px solid #e2e8f0;
  }

  .results-info {
    color: #4a5568;
    font-size: 14px;
  }

  .sort-options {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .sort-options label {
    color: #4a5568;
    font-size: 14px;
  }

  /* 课程网格 */
  .course-card {
    margin-bottom: 25px;
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s;
    cursor: pointer;
  }

  .course-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }

  .course-image-container {
    position: relative;
    height: 150px;
    overflow: hidden;
  }

  .course-image-container .course-image {
    width: 100%;
    height: 150px;
  }

  .course-badge {
    position: absolute;
    top: 10px;
    left: 10px;
    background: rgba(255, 69, 0, 0.9);
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
  }

  .course-level {
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
  }

  .course-content {
    padding: 16px;
  }

  .course-title {
    font-size: 1.1rem;
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 8px;
    line-height: 1.4;
  }

  .course-description {
    color: #718096;
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 12px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .course-meta {
    margin-bottom: 12px;
  }

  .instructor {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
  }

  .instructor-avatar {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    object-fit: cover;
  }

  .instructor span {
    font-size: 14px;
    color: #4a5568;
  }

  .course-stats {
    display: flex;
    gap: 12px;
    font-size: 12px;
    color: #718096;
  }

  .course-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .course-price {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .current-price {
    font-size: 1.1rem;
    font-weight: 600;
    color: #e53e3e;
  }

  .original-price {
    font-size: 14px;
    color: #a0aec0;
    text-decoration: line-through;
  }

  .course-type {
    font-size: 12px;
    color: #3182ce;
    background: #ebf8ff;
    padding: 4px 8px;
    border-radius: 12px;
  }

  /* 响应式设计 */
  @media (max-width: 1024px) {
    .courses-grid {
      grid-template-columns: repeat(3, 1fr);
    }
  }

  @media (max-width: 768px) {
    .courses-grid {
      grid-template-columns: repeat(2, 1fr);
      gap: 15px;
    }

    .filter-group {
      flex-direction: column;
      gap: 10px;
    }

    .filter-label {
      min-width: auto;
    }

    .results-header {
      flex-direction: column;
      gap: 10px;
      align-items: flex-start;
    }
  }

  @media (max-width: 480px) {
    .courses-grid {
      grid-template-columns: 1fr;
    }

    .search-bar {
      flex-direction: column;
    }
  }

  .loading {
    text-align: center;
    padding: 40px;
    color: #7f8c8d;
  }

  .spinner {
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-left-color: #4cb69b;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
    margin: 50px auto 20px;
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }

  .empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #7f8c8d;
  }

  .empty-icon {
    font-size: 80px;
    color: #ddd;
    margin-bottom: 20px;
  }

  .empty-title {
    font-size: 24px;
    margin-bottom: 15px;
    color: #95a5a6;
  }

  .empty-desc {
    font-size: 16px;
    max-width: 500px;
    margin: 0 auto 30px;
  }
</style>
